package com.ice.app.base.authorization.handler;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ice.app.base.authorization.entity.UserSecurtiyDetails;
import com.ice.app.system.auth.service.AuthService;
import com.iceframework.core.entity.Result;

/**
 * 处理登录验证成功的类
 * @author Palo
 *
 */
@Component
public class IceAuthSuccessHandler implements AuthenticationSuccessHandler {

	protected Logger logger = LoggerFactory.getLogger(IceAuthSuccessHandler.class);
	
	@Autowired
    private ObjectMapper objectMapper;

	@Resource
	private AuthService authService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
		UserSecurtiyDetails userDetails = (UserSecurtiyDetails) authentication.getPrincipal();
		Result result = null;
		try {
			result = authService.createAuthenticationToken(userDetails.getUsername());
			response.getWriter().write(objectMapper.writeValueAsString(result));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}